<template>
  <div>
    <van-nav-bar :title="id?'编辑地址':'新增地址'"   left-arrow @click-left='$router.back()'>
      <template #right>
        <van-icon name="ellipsis" />
      </template>
    </van-nav-bar>
    <!-- 地址编辑 -->
    <van-address-edit :address-info="info"  :area-list="areaList" :show-delete="id? true : false" show-set-default
    :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete" />

  </div>
</template>

<script setup>
import { areaList } from "@vant/area-data"
import { addAddress,getAddressDetail,updateAddress,removeAddress } from "../../api/index.js"
import { useRouter,useRoute } from "vue-router"
import { showToast } from 'vant'
import { ref } from "vue"

let router = useRouter();
let route = useRoute();
let id = route.query.addressId;
let info = ref({})


console.log(id);
if (id) {
 getDetail();
}

async function getDetail() {
  let { data } = await getAddressDetail(id)
  info.value = {
    id: data.addressId,
    name: data.userName,
    tel: data.userPhone,
    province: data.provinceName,
    city: data.cityName,
    country: data.countryName,
    addressDetail: data.detailAddress,
    isDefault:data.defaultFlag ? true : false,
  }
}
let onSave = (obj) => {
  let option = {
    "cityName": obj.city,
    "defaultFlag": obj.isDefault ? 1 : 0,
    "detailAddress": obj.addressDetail,
    "provinceName": obj.province,
    "regionName": obj.count,
    "userName": obj.name,
    "userPhone": obj.tel,
    "areaCode": obj.areaCode,
    "postalCode":""
  }
  if (id) {
    updateAddress({ addressId: id, ...option }).then((res) => {
      if (res.resultCode === 200) {
        showToast('编辑成功')
        router.push("/addressList")
      }
    })
  } else {
  addAddress({ ...option }).then(result => {
    if (result.resultCode == 200) {
      showToast('添加成功')
       router.push('/addressList')
    }

 })
}

}
let onDelete = (item) => {
  removeAddress(item.id).then(res => {
    if (res.resultCode === 200) {
      showToast("删除成功")
      setTimeout(() => {
        router.back();
      },500)
    }

  })
}
</script>

<style lang="scss" scoped>

</style>